package com.example.latch;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

public class LeaderLatch implements Latch {

    private RedissonClient redissonClient;

    private RLock rLock;

    private String lockKey;

    private LeaderLatchListener listener;

    private Thread thread;

    public LeaderLatch(RedissonClient redissonClient, String lockKey, LeaderLatchListener listener) {
        this.redissonClient = redissonClient;
        this.lockKey = lockKey;
        this.listener = listener;
    }

    @Override
    public void start() {
        this.thread = new Thread(new Runnable() {
            @Override
            public void run() {
                rLock = redissonClient.getLock(lockKey);
                rLock.lock();
                listener.isLeader();
            }
        });
        this.thread.start();
    }

    @Override
    public void stop() {
        if (this.rLock != null) {
            this.rLock.unlock();
        }
        if (this.thread.isAlive()) {
            this.thread.interrupt();
        }
    }
}
